<?php

namespace App\Admin\Controllers;

use SmallRuralDog\Admin\Controllers\AdminController;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use SmallRuralDog\Admin\Form;
use SmallRuralDog\Admin\Grid;
use SmallRuralDog\Admin\Auth\Database\Menu;
use SmallRuralDog\Admin\Components\Attrs\SelectOption;
use SmallRuralDog\Admin\Components\Form\IconChoose;
use SmallRuralDog\Admin\Components\Form\InputNumber;
use SmallRuralDog\Admin\Components\Form\Select;
use SmallRuralDog\Admin\Components\Form\Radio;
use SmallRuralDog\Admin\Components\Form\RadioGroup;
use SmallRuralDog\Admin\Components\Grid\Avatar;
use SmallRuralDog\Admin\Components\Grid\Icon;
use SmallRuralDog\Admin\Components\Grid\Tag;
use SmallRuralDog\Admin\Components\Grid\Image;
use SmallRuralDog\Admin\Grid\Actions\ActionButton;
use SmallRuralDog\Admin\Components\Widgets\Dialog;
use SmallRuralDog\Admin\Components\Widgets\BaseForm;
use SmallRuralDog\Admin\Components\Form\Input;
use SmallRuralDog\Admin\Components\Form\Upload;
use Illuminate\Support\Facades\Artisan;

// use SimpleSoftwareIO\QrCode\Generator;
use Illuminate\Filesystem\Filesystem;

// use Endroid\QrCode\ErrorCorrectionLevel;
// use Endroid\QrCode\LabelAlignment;
// use Endroid\QrCode\QrCode;
// use Endroid\QrCode\Response\QrCodeResponse;

use SmallRuralDog\Admin\Layout\Content;
use App\Models\Member;
// use App\Models\MemberScoreLog;
// use App\Models\MemberBindAdmin;

class MemberController extends AdminController
{
    protected function grid()
    {
        $grid = new Grid(new Member());
        $grid->column('member_id', "会员ID")->width(80);
        $grid->column('username', "用户名");

        // $grid->column('password', "密码");
        $grid->column('headimgurl', "头像")->width(80)->align('center')->component(Avatar::make());
        $grid->column('nickname', "昵称");
        $grid->column('sex', "性别")->customValue(function ($row, $value) {
            $sex_name = ['0' => '未知', '1' => '男', '2' => '女'];
            return $sex_name[$value];
        })->width(80);
        // $grid->column('committees', "所属居委");
        $grid->column('mobile', "手机");
        // $grid->column('score', "积分")->sortable();
        // $grid->column('qrcode', "会员二维码")->width(80)->align('center')->component(Image::make()->size(50, 50)->preview());
        $grid->column('created_at', "注册时间")->sortable();

        $grid->actions(function (Grid\Actions $actions){
            // $actions->add(ActionButton::make("积分")->order(4)->dialog(function (Dialog $dialog) use ($actions) {
            //     $dialog->title("调整积分")->showClose(true)->width('500px');
            //     $dialog->slot(function (Content $content) use ($actions) {
            //         $baseForm = new BaseForm();
            //         $baseForm->action(route("admin.member.score"));
            //         $baseForm->emit("tableReload");
            //         $baseForm->emit("closeDialog");
            //         $baseForm->addValue("member_id", $actions->getRow()->member_id);
            //         $baseForm->item("score", "积分")->inputWidth(80)->help('积分为负数时则扣减积分');
            //         $baseForm->item("remark", "说明")->required();

            //         $content->row($baseForm);
            //     });
            // }));
        })->toolbars(function (Grid\Toolbars $toolbars)
        {
            // $toolbars->hideCreateButton();
        });

        $grid->quickSearch('username', 'nickname');
        $grid->quickSearchPlaceholder("请输入用户名或昵称");

        return $grid;
    }

    public function form()
    {
        $form = new Form(new Member());

        $connection = config('admin.database.connection');
        // $form->item('username', "姓名")->inputWidth(5);
        $form->item('username', '用户名')
            ->serveCreationRules(['required', "unique:{$connection}.members"])
            ->serveUpdateRules(['required', "unique:{$connection}.members,username,{{id}},member_id"])
            ->component(Input::make());
        $form->item('password', '密码')->serveCreationRules(['required', 'string', 'confirmed'])->serveUpdateRules(['confirmed'])->ignoreEmpty()
            ->component(function () {
                return Input::make()->password()->showPassword();
            });
        $form->item('password_confirmation', '确认密码')
            ->copyValue('password')->ignoreEmpty()
            ->component(function () {
                return Input::make()->password()->showPassword();
            });

        $form->item('headimgurl', "头像")->component(Upload::make()->avatar()->path('avatar')->uniqueName());
        $form->item('nickname', "昵称")->required()->inputWidth(5);
        $form->item('openid', "openid")->inputWidth(5);
        $form->item('sex', "性别")->component(RadioGroup::make(1, [
            Radio::make(0, "未知"),
            Radio::make(1, "男"),
            Radio::make(2, "女"),
        ]));
        // $form->item('email', "邮箱")->inputWidth(5);
        $form->item('mobile', "手机")->inputWidth(5);
        // $form->item('committees', "所属居委")->inputWidth(5);
        // $form->item('bind.isbind', '关联为员工')->component(RadioGroup::make(0, [
        //     Radio::make(1, "是"),
        //     Radio::make(0, "否"),
        // ]));

        // $form->item('bind.admin_id', "员工列表")->component(Select::make(null)->filterable()->options(function () {
        //     $users_model = config('admin.database.users_model');
        //     return $users_model::query()->orderBy('id')->get()->map(function ($item) {
        //         return SelectOption::make($item->id, $item->name)->avatar(admin_file_url($item->avatar));
        //     })->all();
        // }))->vif("bind.isbind", "1");

        $form->saving(function (Form $form)
        {
            $member = $form->model();
            // dd($form->password, $member->id);

            if (isset($member->member_id) && $member->member_id)
            {
                if ($form->password != $member->password)
                {
                    $form->password = bcrypt($form->password);
                }
            }
            else
            {
                $form->password = bcrypt($form->password);
            }


            // if (!$member->qrcode)
            // {

            //     $store_path = storage_path('app/public/member/');
            //     $file = new Filesystem();
            //     if (!$file->exists($store_path) )
            //     {
            //         $file->makeDirectory($store_path, 0777, true, true);
            //     }
            //     $name = $member->openid . '.png';
            //     $code = 'MEMBER|||'.$member->openid;
            //     // $qrcode = new Generator;
            //     // $qrcode = $qrcode->format('png')->size(399)->color(40,40,40)->generate($code, $store_path . $name);
            //     $qrCode = new QrCode($code);
            //     $qrCode->setSize(300);
            //     $qrCode->setWriterByName('png');
            //     $qrCode->setEncoding('UTF-8');
            //     $qrCode->setErrorCorrectionLevel(ErrorCorrectionLevel::HIGH());
            //     $qrCode->setForegroundColor(['r' => 221, 'g' => 82, 'b' => 77, 'a' => 0]);
            //     $qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);
            //     $qrCode->setLogoPath($member->headimgurl);
            //     $qrCode->setLogoSize(80, 80);
            //     $qrCode->setValidateResult(false);

            //     $qrCode->setRoundBlockSize(false);
            //     $qrCode->setMargin(10);
            //     // $qrCode->setWriterOptions(['exclude_xml_declaration' => true]);
            //     $qrCode->writeFile($store_path.'/'.$name);

            //     $qrcode_url = 'member/' . $name;

            //     $form->qrcode = $qrcode_url;
            // }
        });

        $form->DbTransaction(function (form $form) {
            $member = $form->model();
            // $admin_id = $form->input("bind.admin_id") ?? 0;
            // $isbind = $form->input("bind.isbind") ?? 0;

            // try {
            //     if ($isbind && $admin_id)
            //     {
            //         MemberBindAdmin::query()
            //             ->where('member_id', $member->member_id)
            //             ->where('admin_id', $admin_id)
            //             ->updateOrCreate([], [
            //                 'member_id' => $member->member_id,
            //                 'admin_id' => $admin_id,
            //                 'isbind' => $isbind,
            //             ]);
            //     }

            // } catch (\Exception $exception) {

            //     abort(400, '关联员工失败' . config('app.debug') ? $exception->getMessage() : '');

            // }
        });

        return $form;
    }

    // public function getScore(Request $request)
    // {
    //     try {
    //         \Admin::validatorData($request->all(), [
    //             'score' => 'required',
    //             'remark' => 'required',
    //             'member_id' => 'required',
    //         ]);

    //         $member_id = $request->input('member_id');
    //         $score = $request->input('score');
    //         $remark = $request->input('remark');

    //         // 更新会员表
    //         $model_member = Member::query()->findOrFail($member_id);
    //         $model_member->score = intval($model_member->score + $score) > 0 ? intval($model_member->score + $score) : 0;

    //         if( $model_member->save() )
    //         {
    //             // 记录积分日志
    //             MemberScoreLog::create([
    //                 'member_id' => $member_id,
    //                 'action' => $score >= 0 ? 'increase' : 'reduce',
    //                 'score' => intval($score),
    //                 'current_score' => $model_member->score,
    //                 'remark' => '系统 '.$remark,
    //             ]);
    //         }

    //     }
    //     catch (\Exception $exception)
    //     {
    //         return \Admin::responseError($exception->getMessage());
    //     }

    //     // return \Admin::responseRedirect(url('admin#/member'), false, '修改成功', 'success');
    //     return \Admin::responseMessage('修改成功');
    // }

}
